<script setup>
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { registerSalaryStandard } from '@/api/salary'
import { getOrganizationOptions, getOrganizationList } from '@/api/system'
import { getPositionOptions, getPositionList } from '@/api/system'

const formRef = ref()
const formData = ref({
  standardCode: '',
  standardName: '',
  organization: '', // 机构名称
  organizationCode: '', // 机构代码（用于下拉框绑定）
  organizationId: '', // 机构ID（数字，用于提交）
  position: '', // 职位名称
  positionCode: '', // 职位代码（用于下拉框绑定）
  positionId: '', // 职位ID（数字，用于提交）
  effectiveDate: null,
})

// 生成基于时间的标准编号（格式：SAL + YYYYMMDDHHmmss）
const generateStandardCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  return `SAL${year}${month}${day}${hours}${minutes}${seconds}`
}

// 所有可用的薪酬项目（根据接口文档和示例调整）
const allSalaryItems = ref([
  {
    key: 'baseSalary',
    label: '基本工资',
    itemName: '基本工资',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'positionSalary',
    label: '岗位工资',
    itemName: '岗位工资',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'performanceBonus',
    label: '绩效奖金',
    itemName: '绩效奖金',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'allowance',
    label: '津贴',
    itemName: '津贴',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'transportationAllowance',
    label: '交通补贴',
    itemName: '交通补贴',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'mealAllowance',
    label: '餐费补贴',
    itemName: '餐费补贴',
    type: '应发项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'socialSecurity',
    label: '社保',
    itemName: '社保',
    type: '扣款项目',
    checked: false,
    amount: 0,
    calculation: '基本工资*8%',
  },
  {
    key: 'housingFund',
    label: '公积金',
    itemName: '公积金',
    type: '扣款项目',
    checked: false,
    amount: 0,
    calculation: '基本工资*12%',
  },
  {
    key: 'tax',
    label: '个税',
    itemName: '个税',
    type: '扣款项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
  {
    key: 'deduction',
    label: '其他扣除',
    itemName: '其他扣除',
    type: '扣款项目',
    checked: false,
    amount: 0,
    calculation: '',
  },
])

// 选中的薪酬项目
const selectedItems = computed(() => {
  return allSalaryItems.value.filter((item) => item.checked)
})

// 机构选项
const organizationOptions = ref([])
const organizationLoading = ref(false)
// 机构 code 到数字 id 的映射
const organizationCodeToIdMap = ref({})

// 职位选项
const positionOptions = ref([])
const positionLoading = ref(false)
// 职位 code 到数字 id 的映射
const positionCodeToIdMap = ref({})

// 获取机构选项
const fetchOrganizationOptions = async () => {
  organizationLoading.value = true
  try {
    // 获取机构选项（用于下拉选择）
    const optionsResponse = await getOrganizationOptions()
    if (optionsResponse && Array.isArray(optionsResponse.list)) {
      organizationOptions.value = optionsResponse.list.map((item) => ({
        value: item.value,
        label: item.label,
        code: item.value, // 保存 code 用于映射
      }))
    } else {
      organizationOptions.value = []
    }

    // 获取机构列表（用于建立 code 到数字 id 的映射）
    const listResponse = await getOrganizationList()
    if (listResponse && listResponse.list) {
      // 扁平化机构列表
      const flattenOrganizations = (orgs) => {
        const result = []
        orgs.forEach((org) => {
          result.push({
            id: org.id,
            code: org.code,
          })
          if (org.children && org.children.length > 0) {
            result.push(...flattenOrganizations(org.children))
          }
        })
        return result
      }

      const flattenedList = flattenOrganizations(listResponse.list)
      // 建立 code 到数字 id 的映射
      flattenedList.forEach((org) => {
        const numId = typeof org.id === 'number' ? org.id : parseInt(org.id, 10)
        if (!isNaN(numId)) {
          organizationCodeToIdMap.value[org.code] = numId
        }
      })
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    organizationOptions.value = []
  } finally {
    organizationLoading.value = false
  }
}

// 获取职位选项
const fetchPositionOptions = async () => {
  positionLoading.value = true
  try {
    // 获取职位选项（用于下拉选择）
    const optionsResponse = await getPositionOptions()
    if (optionsResponse && Array.isArray(optionsResponse.list)) {
      positionOptions.value = optionsResponse.list.map((item) => ({
        value: item.value,
        label: item.label,
        code: item.value, // 保存 code 用于映射
      }))
    } else {
      positionOptions.value = []
    }

    // 获取职位列表（用于建立 code 到数字 id 的映射）
    const listResponse = await getPositionList()
    if (listResponse && listResponse.list) {
      // 建立 code 到数字 id 的映射
      listResponse.list.forEach((position) => {
        const numId = typeof position.id === 'number' ? position.id : parseInt(position.id, 10)
        if (!isNaN(numId)) {
          positionCodeToIdMap.value[position.code] = numId
        }
      })
    }
  } catch (error) {
    console.error('获取职位选项失败:', error)
    positionOptions.value = []
  } finally {
    positionLoading.value = false
  }
}

// 处理机构选择变化
const handleOrganizationChange = (value) => {
  formData.value.organizationCode = value || ''
  const selectedOrg = organizationOptions.value.find((opt) => opt.value === value)
  if (selectedOrg) {
    formData.value.organization = selectedOrg.label
    // 通过映射表获取数字 id
    const numId = organizationCodeToIdMap.value[selectedOrg.code]
    if (numId !== undefined && !isNaN(numId)) {
      formData.value.organizationId = numId
    } else {
      console.warn('未找到机构对应的数字 ID:', selectedOrg.code)
      formData.value.organizationId = ''
    }
  } else {
    formData.value.organization = ''
    formData.value.organizationId = ''
  }
}

// 处理职位选择变化
const handlePositionChange = (value) => {
  formData.value.positionCode = value || ''
  const selectedPos = positionOptions.value.find((opt) => opt.value === value)
  if (selectedPos) {
    formData.value.position = selectedPos.label
    // 通过映射表获取数字 id
    const numId = positionCodeToIdMap.value[selectedPos.code]
    if (numId !== undefined && !isNaN(numId)) {
      formData.value.positionId = numId
    } else {
      console.warn('未找到职位对应的数字 ID:', selectedPos.code)
      formData.value.positionId = ''
    }
  } else {
    formData.value.position = ''
    formData.value.positionId = ''
  }
}

// 切换薪酬项目选中状态
const toggleSalaryItem = (item) => {
  item.checked = !item.checked
  if (!item.checked) {
    item.amount = 0
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  // 重置时重新生成标准编号
  formData.value = {
    standardCode: generateStandardCode(),
    standardName: '',
    organization: '',
    organizationCode: '',
    organizationId: '',
    position: '',
    positionCode: '',
    positionId: '',
    effectiveDate: null,
  }
  allSalaryItems.value.forEach((item) => {
    item.checked = false
    item.amount = 0
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    // 验证是否至少选择了一个薪酬项目
    if (selectedItems.value.length === 0) {
      message.warning('请至少选择一个薪酬项目')
      return
    }

    // 验证选中的项目是否都填写了金额
    const invalidItems = selectedItems.value.filter(
      (item) =>
        item.amount === undefined ||
        item.amount === null ||
        item.amount === '' ||
        (typeof item.amount === 'number' && item.amount < 0),
    )
    if (invalidItems.length > 0) {
      const itemNames = invalidItems.map((item) => item.label).join('、')
      message.warning(`请填写以下薪酬项目的金额：${itemNames}`)
      return
    }

    // 验证必填字段
    if (!formData.value.standardCode) {
      message.warning('标准编号不能为空')
      return
    }
    if (!formData.value.organizationCode || !formData.value.organizationId) {
      message.warning('请选择适用机构')
      return
    }
    if (!formData.value.positionCode || !formData.value.positionId) {
      message.warning('请选择适用职位')
      return
    }
    if (!formData.value.effectiveDate) {
      message.warning('请选择生效日期')
      return
    }

    // 格式化生效日期
    let effectiveDateStr
    if (typeof formData.value.effectiveDate === 'string') {
      effectiveDateStr = formData.value.effectiveDate
    } else if (formData.value.effectiveDate && typeof formData.value.effectiveDate.format === 'function') {
      // dayjs 对象
      effectiveDateStr = formData.value.effectiveDate.format('YYYY-MM-DD')
    } else if (formData.value.effectiveDate instanceof Date) {
      // Date 对象
      const year = formData.value.effectiveDate.getFullYear()
      const month = String(formData.value.effectiveDate.getMonth() + 1).padStart(2, '0')
      const day = String(formData.value.effectiveDate.getDate()).padStart(2, '0')
      effectiveDateStr = `${year}-${month}-${day}`
    } else {
      message.warning('生效日期格式不正确')
      return
    }

    // 准备提交数据（按照接口文档格式）
    const submitData = {
      standardCode: formData.value.standardCode,
      standardName: formData.value.standardName,
      organization: formData.value.organization,
      organizationId: formData.value.organizationId,
      position: formData.value.position,
      positionId: formData.value.positionId,
      effectiveDate: effectiveDateStr,
      items: selectedItems.value.map((item) => ({
        itemName: item.itemName,
        amount: item.amount,
      })),
    }

    console.log('提交薪酬标准登记数据:', submitData)

    try {
      const response = await registerSalaryStandard(submitData)
      console.log('薪酬标准登记响应:', response)

      message.success('薪酬标准登记成功，已提交复核')
      handleReset()
    } catch (error) {
      console.error('提交登记失败:', error)
      // handleApiError 已经处理了错误提示
    }
  } catch (err) {
    if (err?.errorFields) {
      return
    }
    message.error('提交失败，请稍后重试')
  }
}

onMounted(() => {
  // 初始化时生成标准编号
  formData.value.standardCode = generateStandardCode()
  fetchOrganizationOptions()
  fetchPositionOptions()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">薪酬标准登记</h1>
      <p class="page-desc">建立和维护各职位薪酬标准，填写完成后将提交复核</p>
    </div>

    <div class="page-content">
      <a-card class="form-card">
        <a-form
          ref="formRef"
          :model="formData"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <!-- 基本信息 -->
          <a-card title="标准基本信息" class="section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="薪酬标准编号"
                  name="standardCode"
                  :rules="[{ required: true, message: '标准编号不能为空' }]"
                >
                  <a-input
                    v-model:value="formData.standardCode"
                    placeholder="系统自动生成"
                    readonly
                    style="background-color: #f5f5f5; cursor: not-allowed"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="薪酬标准名称"
                  name="standardName"
                  :rules="[{ required: true, message: '请输入标准名称' }]"
                >
                  <a-input
                    v-model:value="formData.standardName"
                    placeholder="请输入标准名称"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="适用机构"
                  name="organizationCode"
                  :rules="[{ required: true, message: '请选择适用机构' }]"
                >
                  <a-select
                    v-model:value="formData.organizationCode"
                    placeholder="请选择适用机构"
                    allow-clear
                    :loading="organizationLoading"
                    @change="handleOrganizationChange"
                  >
                    <a-select-option
                      v-for="option in organizationOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="适用职位"
                  name="positionCode"
                  :rules="[{ required: true, message: '请选择适用职位' }]"
                >
                  <a-select
                    v-model:value="formData.positionCode"
                    placeholder="请选择职位"
                    allow-clear
                    :loading="positionLoading"
                    @change="handlePositionChange"
                  >
                    <a-select-option
                      v-for="option in positionOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="生效日期"
                  name="effectiveDate"
                  :rules="[{ required: true, message: '请选择生效日期' }]"
                >
                  <a-date-picker
                    v-model:value="formData.effectiveDate"
                    style="width: 100%"
                    placeholder="请选择生效日期"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 选择薪酬项目 -->
          <a-card title="选择薪酬项目" class="section-card" :bordered="false">
            <div class="salary-items-container">
              <div class="items-section">
                <div class="section-title">应发项目</div>
                <div class="salary-items-grid">
                  <div
                    v-for="item in allSalaryItems.filter((i) => i.type === '应发项目')"
                    :key="item.key"
                    class="salary-item-checkbox"
                    :class="{ 'item-selected': item.checked }"
                    @click="toggleSalaryItem(item)"
                  >
                    <a-checkbox
                      :checked="item.checked"
                      @change="toggleSalaryItem(item)"
                      @click.stop
                    >
                      {{ item.label }}
                    </a-checkbox>
                  </div>
                </div>
              </div>
              <div class="items-section">
                <div class="section-title">扣款项目</div>
                <div class="salary-items-grid">
                  <div
                    v-for="item in allSalaryItems.filter((i) => i.type === '扣款项目')"
                    :key="item.key"
                    class="salary-item-checkbox"
                    :class="{ 'item-selected': item.checked }"
                    @click="toggleSalaryItem(item)"
                  >
                    <a-checkbox
                      :checked="item.checked"
                      @change="toggleSalaryItem(item)"
                      @click.stop
                    >
                      {{ item.label }}
                    </a-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 薪酬项目明细 -->
          <a-card
            v-if="selectedItems.length > 0"
            title="薪酬项目明细"
            class="section-card"
            :bordered="false"
          >
            <div class="detail-sections">
              <!-- 应发项目明细 -->
              <div
                v-if="selectedItems.filter((i) => i.type === '应发项目').length > 0"
                class="detail-section"
              >
                <div class="detail-section-title">应发项目</div>
                <a-row :gutter="24">
                  <a-col
                    v-for="item in selectedItems.filter((i) => i.type === '应发项目')"
                    :key="item.key"
                    :span="12"
                    class="salary-detail-item"
                  >
                    <a-form-item
                      :label="item.label"
                    >
                      <a-input-number
                        v-model:value="item.amount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                        placeholder="0.00"
                        :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                      >
                        <template #prefix>¥</template>
                      </a-input-number>
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>

              <!-- 扣款项目明细 -->
              <div
                v-if="selectedItems.filter((i) => i.type === '扣款项目').length > 0"
                class="detail-section"
              >
                <div class="detail-section-title">扣款项目</div>
                <a-row :gutter="24">
                  <a-col
                    v-for="item in selectedItems.filter((i) => i.type === '扣款项目')"
                    :key="item.key"
                    :span="12"
                    class="salary-detail-item"
                  >
                    <a-form-item
                      :label="item.label"
                    >
                      <a-input-number
                        v-model:value="item.amount"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                        placeholder="0.00"
                        :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                      >
                        <template #prefix>¥</template>
                      </a-input-number>
                      <div v-if="item.calculation" class="calculation-hint">
                        <span class="hint-icon">💡</span>
                        计算方式：{{ item.calculation }}
                      </div>
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-card>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <a-button size="large" @click="handleReset">重置</a-button>
            <a-button type="primary" size="large" @click="handleSubmit">提交登记</a-button>
          </div>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.form-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
  border: none;
}

.section-card {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
  transition: all 0.3s;
}

.section-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
}

.section-card :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.section-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.section-card :deep(.ant-card-body) {
  padding: 24px;
}

.salary-items-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.items-section {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #1890ff;
  display: inline-block;
}

.salary-items-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.salary-item-checkbox {
  padding: 14px 16px;
  border: 2px solid rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  background: #fff;
  transition: all 0.3s;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.salary-item-checkbox:hover {
  border-color: #1890ff;
  background: #f0f8ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.15);
}

.salary-item-checkbox.item-selected {
  border-color: #1890ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.salary-item-checkbox :deep(.ant-checkbox-wrapper) {
  width: 100%;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}

.salary-item-checkbox.item-selected :deep(.ant-checkbox-wrapper) {
  color: #1890ff;
}

.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.detail-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #52c41a;
  display: inline-block;
}

.detail-section:last-child .detail-section-title {
  border-bottom-color: #ff4d4f;
}

.salary-detail-item {
  margin-bottom: 16px;
}

.salary-detail-item :deep(.ant-form-item-label) {
  font-weight: 500;
}

.salary-detail-item :deep(.ant-input-number) {
  border-radius: 6px;
}

.salary-detail-item :deep(.ant-input-number:hover) {
  border-color: #1890ff;
}

.calculation-hint {
  font-size: 12px;
  color: #86868b;
  margin-top: 6px;
  padding: 6px 10px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.hint-icon {
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.form-actions :deep(.ant-btn) {
  min-width: 120px;
  height: 40px;
  border-radius: 6px;
  font-weight: 500;
}

.form-actions :deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.form-actions :deep(.ant-btn-primary:hover) {
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  transform: translateY(-1px);
}
</style>
